package com.itttq.kb.service;

import java.security.NoSuchAlgorithmException;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.itttq.kb.mapper.IUserMapper;
import com.itttq.kb.model.po.UserPo;
import com.itttq.kb.model.to.PageParamTo;
import com.itttq.kb.model.to.ResultDataTo;
import com.itttq.kb.model.to.ResultTo;
import com.itttq.kb.utils.Constants;
import com.itttq.kb.utils.EncryptUtil;

@Service
public class UserService {
	@Autowired
	private IUserMapper userMapper;
	
	public UserPo getUser(int id) {
		UserPo user = new UserPo();
		user.setId(id);
		return userMapper.findById(user);
	}
	
	/**
	 * 用户注册，密码为用户设置密码 + 散列值进行md5加密
	 * 
	 * @param username
	 * @param pwd
	 * @return
	 * @Author 迷蝶
	 * @return ResultTo
	 */
	public ResultDataTo<UserPo> login(String username, String pwd) {
		ResultDataTo<UserPo> rt = new ResultDataTo<UserPo>(ResultTo.FAIL, "发生错误！");
		if(StringUtils.isBlank(username) || StringUtils.isBlank(pwd)) {
//			rt.setCode(ResultTo.PARAM_INCORRECT);
			rt.setMsg("用户名或密码不能为空！");
			return rt;
		}
		UserPo user = new  UserPo();
		user.setUsername(username);
		List<UserPo> users = userMapper.find4page(user, new  PageParamTo());
		if(null != users && users.size() > 0) {
			try {
				if(EncryptUtil.getPassword(pwd, users.get(0).getSalt()).equals(users.get(0).getPassword())) {
					rt.setCode(ResultTo.SUCCESS);
					rt.setMsg("登录成功！");
					rt.setData(users.get(0));
				} else {
					rt.setMsg("用户名或密码错误！");
				}
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
		}
		return rt;
	}
	
	public List<UserPo> getUsers(UserPo user, PageParamTo ppt) {
		return userMapper.find4page(user, ppt);
	}

	public int getUserCount(UserPo user) {
		return userMapper.getCount(user);
	}

	public void delUser(int id) {
		UserPo user = new UserPo();
		user.setId(id);
		userMapper.delete(user);
	}

	/**
	 * 增加用户
	 * 
	 * @param user
	 * @throws NoSuchAlgorithmException
	 * @Author 迷蝶
	 * @return void
	 */
	public void addUser(UserPo user) throws NoSuchAlgorithmException {
		// 获取散列值
		user.setSalt(Constants.genRandomNum(6));
		// 处理密码
		user.setPassword(EncryptUtil.getPassword(user.getPassword(), user.getSalt()));
		userMapper.insert(user);
	}
	
	public void updateUser(UserPo user) {
		userMapper.update(user);
	}
	
	public void modifyPwd(String newPwd, int uid) throws NoSuchAlgorithmException {
		String slat = Constants.genRandomNum(6);
		userMapper.modifyPwd(EncryptUtil.getPassword(newPwd, slat), slat, uid);
	}
}
